<script setup lang="ts">
import * as echarts from 'echarts';
import { ref, onMounted, onUnmounted, watch } from 'vue';
import {
  panChartData,
  moneyTreeChartData,
  countTreeChartData,
  employeePerformanceChartData,
  getData
} from '@/components/Store/useChartDataStore';

// 饼图相关
let panChart: echarts.ECharts | null = null;
const panData = ref([
  { value: 0, name: '售出' },
  { value: 0, name: '购入' },
  { value: 0, name: '划拨' }
]);

// 金额柱状图相关
let moneyBarChart: echarts.ECharts | null = null;
const moneyBarData = ref<{ name: string; outValue: number; inValue: number }[]>([]);

// 数量柱状图相关
let countBarChart: echarts.ECharts | null = null;
const countBarData = ref<{ name: string; outValue: number; inValue: number }[]>([]);

// 员工业绩折线图相关
let employeePerfChart: echarts.ECharts | null = null;
const employeePerfData = ref<{ name: string; value: number }[]>([]);

// 数据加载状态
const dataLoading = ref(true);

onMounted(async () => {
  // 初始化所有图表实例
  const panChartDom = document.getElementById("panChart");
  if (panChartDom) panChart = echarts.init(panChartDom);

  const moneyBarDom = document.getElementById("moneyBarChart");
  if (moneyBarDom) moneyBarChart = echarts.init(moneyBarDom);

  const countBarDom = document.getElementById("countBarChart");
  if (countBarDom) countBarChart = echarts.init(countBarDom);

  const employeePerfDom = document.getElementById("employeePerfChart");
  if (employeePerfDom) employeePerfChart = echarts.init(employeePerfDom);

  // 添加resize监听器
  window.addEventListener('resize', resizeCharts);

  // 加载数据并更新图表
  await loadDataAndUpdate();
});

onUnmounted(() => {
  // 清理所有图表实例
  disposeChart(panChart);
  disposeChart(moneyBarChart);
  disposeChart(countBarChart);
  disposeChart(employeePerfChart);

  // 移除resize监听器
  window.removeEventListener('resize', resizeCharts);
});

// 监听数据变化
watch(panChartData, updatePanChartData);
watch(moneyTreeChartData, updateMoneyBarData);
watch(countTreeChartData, updateCountBarData);
watch(employeePerformanceChartData, updateEmployeePerfData);

// 辅助函数 - 清理图表
function disposeChart(chart: echarts.ECharts | null) {
  if (chart) {
    chart.dispose();
    chart = null;
  }
}

// 辅助函数 - 调整所有图表尺寸
function resizeCharts() {
  panChart?.resize();
  moneyBarChart?.resize();
  countBarChart?.resize();
  employeePerfChart?.resize();
}

async function loadDataAndUpdate() {
  dataLoading.value = true;
  try {
    await getData();
    updateAllChartsData();
  } finally {
    dataLoading.value = false;
  }
}

function updateAllChartsData() {
  updatePanChartData();
  updateMoneyBarData();
  updateCountBarData();
  updateEmployeePerfData();
}

// 更新饼图数据
function updatePanChartData() {
  if (!panChart) return;

  // 重置数据
  panData.value = [
    { value: 0, name: '售出' },
    { value: 0, name: '购入' },
    { value: 0, name: '划拨' }
  ];

  // 检查是否有数据
  if (!panChartData.value || panChartData.value.length === 0) {
    showNoDataIndicator(panChart, '订单类型饼图');
    return;
  }

  // 计算一个月前的时间点
  const oneMonthAgo = Date.now() - 30 * 24 * 60 * 60 * 1000;

  // 统计数据
  panChartData.value.forEach(item => {
    const itemTime = new Date(item.dealTime).getTime();
    if (itemTime > oneMonthAgo) {
      if (item.name === "售出") panData.value[0].value += 1;
      else if (item.name === "购入") panData.value[1].value += 1;
      else if (item.name === "划拨") panData.value[2].value += 1;
    }
  });

  // 过滤掉值为0的项
  const filteredData = panData.value.filter(item => item.value > 0);

  // 如果没有有效数据，显示提示
  if (filteredData.length === 0) {
    showNoDataIndicator(panChart, '订单类型饼图');
    return;
  }

  // 配置项
  const option = {
    title: {
      text: '订单类型饼图',
      left: 'center',
      top: '2%'
    },
    legend: {
      top: 'bottom'
    },
    toolbox: {
      show: true,
      feature: {
        mark: { show: true },
        dataView: { show: true, readOnly: false },
        restore: { show: true },
        saveAsImage: { show: true }
      }
    },
    series: [
      {
        name: '订单类型',
        type: 'pie',
        radius: ['30%', '60%'],
        center: ['50%', '55%'],
        roseType: 'area',
        itemStyle: {
          borderRadius: 8
        },
        label: {
          show: true,
          formatter: '{b}: {c}'
        },
        data: filteredData
      }
    ]
  };

  panChart.setOption(option);
}

// 更新金额柱状图
function updateMoneyBarData() {
  if (!moneyBarChart) return;

  moneyBarData.value = [];

  // 检查是否有数据
  if (!moneyTreeChartData.value || moneyTreeChartData.value.length === 0) {
    showNoDataIndicator(moneyBarChart, '货物交易金额');
    return;
  }

  // 计算一个月前的时间点
  const oneMonthAgo = Date.now() - 30 * 24 * 60 * 60 * 1000;

  // 按货物名称分组
  const goodsMap = new Map<string, { outValue: number; inValue: number }>();

  moneyTreeChartData.value.forEach(item => {
    const itemTime = new Date(item.dealTime).getTime();
    if (itemTime > oneMonthAgo) {
      if (!goodsMap.has(item.name)) {
        goodsMap.set(item.name, { outValue: 0, inValue: 0 });
      }

      const goodsData = goodsMap.get(item.name)!;
      goodsData.outValue += item.outValue;
      goodsData.inValue += item.inValue;
    }
  });

  // 转换为数组并过滤掉没有数据的商品
  moneyBarData.value = Array.from(goodsMap.entries())//将Map转换为二维数组
      .map(([name, values]) => ({ name, ...values }))//将每个子数组解构为 name，values并合成新的对象
      .filter(item => item.outValue > 0 || item.inValue > 0);//过滤掉没有售出且没有购入的商品

  // 如果没有有效数据，显示提示
  if (moneyBarData.value.length === 0) {
    showNoDataIndicator(moneyBarChart, '货物交易金额');
    return;
  }

  // 配置项
  const option = {
    title: {
      text: '货物交易金额',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['售出金额', '购入金额'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: moneyBarData.value.map(item => item.name)
    },
    yAxis: {
      type: 'value',
      name: '金额（元）'
    },
    series: [
      {
        name: '售出金额',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: moneyBarData.value.map(item => item.outValue)
      },
      {
        name: '购入金额',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: moneyBarData.value.map(item => item.inValue)
      }
    ]
  };

  moneyBarChart.setOption(option);
}

// 更新数量柱状图
function updateCountBarData() {
  if (!countBarChart) return;

  countBarData.value = [];

  // 检查是否有数据
  if (!countTreeChartData.value || countTreeChartData.value.length === 0) {
    showNoDataIndicator(countBarChart, '货物交易数量');
    return;
  }

  // 计算一个月前的时间点
  const oneMonthAgo = Date.now() - 30 * 24 * 60 * 60 * 1000;

  // 按货物名称分组
  const goodsMap = new Map<string, { outValue: number; inValue: number }>();

  countTreeChartData.value.forEach(item => {
    const itemTime = new Date(item.dealTime).getTime();
    if (itemTime > oneMonthAgo) {
      if (!goodsMap.has(item.name)) {
        goodsMap.set(item.name, { outValue: 0, inValue: 0 });
      }

      const goodsData = goodsMap.get(item.name)!;
      goodsData.outValue += item.outValue;
      goodsData.inValue += item.inValue;
    }
  });

  // 转换为数组并过滤掉没有数据的商品
  countBarData.value = Array.from(goodsMap.entries())
      .map(([name, values]) => ({ name, ...values }))
      .filter(item => item.outValue > 0 || item.inValue > 0);

  // 如果没有有效数据，显示提示
  if (countBarData.value.length === 0) {
    showNoDataIndicator(countBarChart, '货物交易数量');
    return;
  }

  // 配置项
  const option = {
    title: {
      text: '货物交易数量',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['售出数量', '购入数量'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: countBarData.value.map(item => item.name)
    },
    yAxis: {
      type: 'value',
      name: '数量'
    },
    series: [
      {
        name: '售出数量',
        type: 'bar',
        emphasis: {
          focus: 'series'
        },
        data: countBarData.value.map(item => item.outValue)
      },
      {
        name: '购入数量',
        type: 'bar',
        emphasis: {
          focus: 'series'
        },
        data: countBarData.value.map(item => item.inValue)
      }
    ]
  };

  countBarChart.setOption(option);
}

// 更新员工业绩折线图
function updateEmployeePerfData() {
  if (!employeePerfChart) return;

  employeePerfData.value = [];

  // 检查是否有数据
  if (!employeePerformanceChartData.value || employeePerformanceChartData.value.length === 0) {
    showNoDataIndicator(employeePerfChart, '员工业绩趋势');
    return;
  }

  // 计算一个月前的时间点
  const oneMonthAgo = Date.now() - 30 * 24 * 60 * 60 * 1000;

  // 按员工名称分组
  const employeeMap = new Map<string, number>();

  employeePerformanceChartData.value.forEach(item => {
    const itemTime = new Date(item.dealTime).getTime();
    if (itemTime > oneMonthAgo) {
      if (!employeeMap.has(item.name)) {
        employeeMap.set(item.name, 0);
      }

      employeeMap.set(item.name, employeeMap.get(item.name)! + item.value);
    }
  });

  // 转换为数组并排序
  employeePerfData.value = Array.from(employeeMap.entries())
      .map(([name, value]) => ({ name, value }))
      .sort((a, b) => b.value - a.value);

  // 如果没有有效数据，显示提示
  if (employeePerfData.value.length === 0) {
    showNoDataIndicator(employeePerfChart, '员工业绩趋势');
    return;
  }

  // 配置项
  const option = {
    title: {
      text: '员工业绩趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['员工业绩'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: employeePerfData.value.map(item => item.name)
    },
    yAxis: {
      type: 'value',
      name: '业绩指数'
    },
    series: [
      {
        name: '员工业绩',
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 3
        },
        data: employeePerfData.value.map(item => item.value)
      }
    ]
  };

  employeePerfChart.setOption(option);
}

// 显示无数据提示
function showNoDataIndicator(chart: echarts.ECharts | null, title: string) {
  if (!chart) return;

  chart.setOption({
    title: {
      text: title,
      subtext: '暂无数据',
      left: 'center',
      top: 'center'
    },
    series: [] // 清空系列数据
  });
}
</script>

<template>
  <div class="dashboard">
    <!-- 第一行：三个图表 -->
    <div class="row">
      <!-- 饼图 -->
      <div class="chart-item">
        <div v-if="dataLoading" class="chart-loading">
          数据加载中...
        </div>
        <div id="panChart" style="width: 100%; height: 350px"></div>
      </div>

      <!-- 金额柱状图 -->
      <div class="chart-item">
        <div v-if="dataLoading" class="chart-loading">
          数据加载中...
        </div>
        <div id="moneyBarChart" style="width: 100%; height: 350px"></div>
      </div>

      <!-- 数量柱状图 -->
      <div class="chart-item">
        <div v-if="dataLoading" class="chart-loading">
          数据加载中...
        </div>
        <div id="countBarChart" style="width: 100%; height: 350px"></div>
      </div>
    </div>

    <!-- 第二行：员工业绩折线图 -->
    <div class="row">
      <div class="chart-item full-width">
        <div v-if="dataLoading" class="chart-loading">
          数据加载中...
        </div>
        <div id="employeePerfChart" style="width: 100%; height: 350px"></div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.dashboard {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  box-sizing: border-box;
  width: 100%;
  max-width: 1400px;
  margin: 0 auto;
}

.row {
  display: flex;
  gap: 20px;
  width: 100%;
}

.chart-item {
  flex: 1;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 16px;
  transition: all 0.3s;
  position: relative;
  min-height: 350px;
}

.full-width {
  flex: 100%;
}

.chart-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 10;
  font-size: 16px;
  color: #666;
}

.chart-item:hover {
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
}

@media (max-width: 992px) {
  .row {
    flex-direction: column;
  }

  .chart-item {
    width: 100%;
  }
}
</style>